package com.icow.wms.basic.utils;

import HslCommunication.Core.Types.OperateResult;
import HslCommunication.Core.Types.OperateResultExOne;
import HslCommunication.Profinet.Siemens.SiemensPLCS;
import HslCommunication.Profinet.Siemens.SiemensS7Net;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class PLCUtils {

    public static boolean readPLC(String ip, String DBAddress) {
        SiemensS7Net siemensS7Net = null;
        try {
            siemensS7Net = new SiemensS7Net(SiemensPLCS.S1500, ip);
            siemensS7Net.setConnectTimeOut(1500);
            siemensS7Net.setReceiveTimeOut(1500);
            OperateResultExOne<Boolean> read = siemensS7Net.ReadBool(DBAddress);
            if (read.IsSuccess) {
                Boolean content = read.Content;
                log.info("ip " + ip + " " + DBAddress + " PLC数据: " + content);
                return content;
            } else {
                log.info("ip " + ip + " " + DBAddress + " 读取失败: " + read.Message);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (siemensS7Net != null) {
                    siemensS7Net.ConnectClose();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return false;
    }


    public static boolean writePLC(String ip, String DBAddress, boolean value) {
        SiemensS7Net siemensS7Net = null;
        try {
            siemensS7Net = new SiemensS7Net(SiemensPLCS.S1500, ip);
            siemensS7Net.setConnectTimeOut(1500);
            siemensS7Net.setReceiveTimeOut(1500);
            OperateResult write = siemensS7Net.Write(DBAddress, value);
            if (write.IsSuccess) {
                log.info("ip " + ip + " " + DBAddress + " 写入数据成功 " + value);
                return true;
            } else {
                log.info("ip " + ip + " " + DBAddress + " 写入数据失败 " + value);
                return false;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (siemensS7Net != null) {
                    siemensS7Net.ConnectClose();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return false;
    }
}
